#pragma once
#include<algorithm>
namespace My_Stl
{
	template<class T>
	struct ListNode
	{
		ListNode* _prev;
		ListNode* _next;
		T _val;

		ListNode()
			:_prev(this)
			,_next(this)
			,_val(T())
		{}
		ListNode(const T& val)
			:_prev(nullptr)
			,_next(nullptr)
			,_val(val)
		{}
	};

	template<class T, class Ref ,class Ptr>
	struct list_iterator
	{
		typedef ListNode<T> Node;
		typedef list_iterator<T, Ref, Ptr> self;
		Node* _node;

		list_iterator(Node* node)
			:_node(node)
		{}
		Ref operator*()
		{
			return _node->_val;
		}
		Ptr operator->()
		{
			return &_node->_val;
		}
		self& operator++()
		{
			_node = _node->_next;
			return *this;
		}
		self operator++(int)
		{
			_node = _node->_next;
			return _node->_prev;
		}
		self& operator--()
		{
			_node = _node->_prev;
			return *this;
		}
		self operator--(int)
		{
			_node = _node->_prev;
			return _node->_next;
		}
		bool operator!=(list_iterator it)
		{
			return _node!=it._node;
		}
	};

	template<class T>
	class list
	{
		typedef ListNode<T> Node;
	public:
		typedef list_iterator<T,T&,T*> iterator;
		typedef list_iterator<T,const T&,const T*> const_iterator;

		list()
			:_head(new Node)
			,_size(0)
		{}
		list(const list<T>& lt)
			:_head(new Node)
			, _size(0)
		{
			for(auto& e : lt)
			{
				push_back(e);
			}
		}

		list<T>& operator=(list<T> lt)
		{
			swap(lt);
			return *this;
		}

		~list()
		{
			clear();
			delete _head;
			_head = nullptr;
		}
		iterator begin()
		{
			return _head->_next;
		}

		iterator end()
		{
			return _head;
		}

		const_iterator begin()const
		{
			return _head->_next;
		}

		const_iterator end()const
		{
			return _head;
		}

		bool empty()const
		{
			return !size();
		}

		size_t size()const
		{
			return _size;
		}

		void swap(list<T>& lt)
		{
			std::swap(_head, lt._head);
			std::swap(_size, lt._size);
		}

		void push_front(const T& val)
		{
			insert(begin(), val);
		}

		void pop_front()
		{
			erase(begin());
		}

		void push_back(const T& val)
		{
			insert(end(), val);
		}

		void pop_back()
		{
			erase(--end());
		}

		iterator insert(iterator position, const T& val)
		{
			++_size;
			Node* node = new Node(val);
			Node* prev = position._node->_prev;
			Node* next = position._node;
			node->_prev = prev;
			node->_next = next;
			prev->_next = node;
			next->_prev = node;
			return node;
		}

		iterator erase(iterator position)
		{
			if(_size == 0)
			{
				return end();
			}
			else
			{
				--_size;
				Node* prev = position._node->_prev;
				Node* next = position._node->_next;
				delete position._node;
				prev->_next = next;
				next->_prev = prev;
				return next;
			}
		}

		void clear()
		{
			iterator it = begin();
			while (it != end())
			{
				it=erase(it);
			}
		}

	private:
		Node* _head;
		size_t _size;
	};
}

